import mxgraph from '@/topology/mxgraph';

const {mxEvent, mxCodec, mxUtils} = mxgraph;

export function Utils() {

}

/**
 * 工具栏按钮事件
 * @param action
 * @param editor
 */
Utils.prototype.toolbarAction = function (action, editor) {
  let button = document.getElementById(action);
  mxEvent.addListener(button, 'click', function (evt) {
    editor.execute(action);
  });
}

/***
 * 获取XML信息
 * @param graph
 */
Utils.prototype.getXml = function (graph) {
  let encoder = new mxCodec();
  let result = encoder.encode(graph.getModel());
  return mxUtils.getXml(result);
}

/**
 * 加载XML
 * @param xml
 * @param graph
 */
Utils.prototype.loadXml = function (xml, graph) {
  let doc = mxUtils.parseXml(xml);
  let codec = new mxCodec(doc);
  codec.decode(doc.documentElement, graph.getModel());
}

/***
 * 拖动新增
 * @param id
 * @param graph
 * @param callback
 */
Utils.prototype.draggable = function (id, graph, callback) {
  let element = document.getElementById(id);
  let ds = mxUtils.makeDraggable(element, graph, function (_graph, evt, target, x, y) {
    if (callback) {
      callback(graph, x, y);
    }
  });
  ds.setGuidesEnabled(true);
}

/***
 * 新增节点信息
 * @param graph
 * @param label
 * @param x
 * @param y
 * @param style
 * @param width
 * @param height
 * @returns {*}
 */
Utils.prototype.insertNode = function (graph, label, x, y, style, width, height) {
  let model = graph.getModel();
  let v1 = null;
  model.beginUpdate();
  try {
    v1 = graph.insertVertex(graph.getDefaultParent(), null, label, x, y, width, height, style)
    v1.setConnectable(true);
  } finally {
    model.endUpdate();
  }
  graph.setSelectionCell(v1);
  return graph;
}

/**
 * 新增线条
 * @param graph
 * @param value
 * @param source
 * @param target
 * @param style
 * @author yzw
 * @date 2021/6/18 下午3:32
 */
Utils.prototype.insertEdge = function (graph, value, source, target, style) {
  graph.insertEdge(graph.getDefaultParent(), null, value, source, target, style)
}


